<?php
/**
 * 样衣采购需求模型
 * @author sundongdong
 * @date 2016-07-19
 */
class Purchase_Model_SampleCloth extends Model_Base {
	/**
	 * 获取样衣需求列表
	 * @param array $filter
	 */
	public function getSampleList(array $filter) {
		$where = "1";
		$params = array();
		if ($filter['key'] != '' && $filter['value'] != '') {
			if ($filter['key'] == 'sku') {
				$skus = explode(',', $filter['value']);
				array_walk($skus, 'trim');// 去除每个sku的空格
				if (count($skus) > 1) {
					$where .= $this->db()->quoteInto(' and sku in (?)', $skus);
				} else {
					if (strlen($skus[0]) >= 7) {
						$where .= $this->db()->quoteInto(' and sku like ?', $skus[0]."%");
					} else {
						$where .= $this->db()->quoteInto(' and sku = ?', $skus[0]);
					}
				}
			} elseif ($filter['key'] == 'supplier_sn') {
				$where .= " and {$filter['key']} = :value";
				$params['value'] = $filter['value'];
			} else {
				$where .= " and {$filter['key']} like :value";
				$params['value'] = "%".$filter['value']."%";
			}
		}
		if ($filter['good_status'] != '') {
			$where .= ' and goods_status = :good_status';
			$params['good_status'] = $filter['good_status'];
		}
		if ($filter['start'] != '' || $filter['end'] != '') {
			if ($filter['start'] == '') {
				$where .= ' and add_time < :end';
				$params['end'] = $filter['end'];
			} elseif ($filter['end'] == '') {
				$where .= ' and add_time > :start';
				$params['start'] = $filter['start'];
			} else {
				$where .= ' and add_time > :start and add_time < :end';
				$params['start'] = $filter['start'];
				$params['end'] = $filter['end'];
			}
		}
		if ($filter['sync_status'] != '') {
			$where .= ' and sync_status = :sync_status';
			$params['sync_status'] = $filter['sync_status'];
		}
		if ($filter['privide_status'] != '') {
			$where .= ' and provide_status = :privide_status';
			$params['privide_status'] = $filter['privide_status'];
		}
		if ($filter['is_extended'] != '') {
			$where .= ' and is_extended = :is_extended';
			$params['is_extended'] = $filter['is_extended'];
		}
		if ($filter['sample_type'] != '') {
			$where .= ' and sample_type = :sample_type';
			$params['sample_type'] = $filter['sample_type'];
		}
		
		$sql = "select * from sample_cloth where " . $where ." order by id";
		$sql = $sql . ' limit '.($filter['page'] - 1) * $filter['perPage'].','.$filter['perPage'];
		$countsql = "select count(1) from sample_cloth where ".$where;
		
		$res = array();
		$res['list'] = $this->db()->fetchAll($sql, $params);
		$res['count'] = $this->db()->fetchOne($countsql, $params);

		return $res;
	}
	/**
	 * 批量推广样衣
	 * @param string $ids
	 */
	public function extendSample(string $ids) {
		$wdb = $this->db('write_db');
		try {
			$param = array(
				'is_extended' => 1
			);
			$wdb->update('sample_cloth', $param, 'id in ('.$ids.')');
			$res = array("opr"=>1,'content'=>"推广成功");
		} catch (Exception $e) {
			$res = array("opr"=>0,'content'=>$e->getMessage());
		}
		return $res;
	}
	/**
	 * 获取FB推广列表
	 * @param array $filter
	 */
	public function getFbList(array $filter) {
		$where = "is_show = 1";
		$params = array();
		if ($filter['sku'] != '') {
			$where .= $this->db()->quoteInto(' and sku = ?', $filter['sku']);
		}
		if ($filter['operate_user'] != '') {
			$where .= $this->db()->quoteInto(' and operate_user like ?', '%'.$filter['operate_user'].'%');
		}
		if ($filter['time_type'] != '' && ($filter['start'] || $filter['end'])) {
			if ($filter['start'] == '') {
				$where .= $this->db()->quoteInto(" and {$filter['time_type']} < ?", $filter['end']);
			} elseif ($filter['end'] == '') {
				$where .= $this->db()->quoteInto(" and {$filter['time_type']} > ?", $filter['start']);
			} else {
				$where .= $this->db()->quoteInto(" and {$filter['time_type']} > ?", $filter['start']) . $this->db()->quoteInto(" and {$filter['time_type']} < ?", $filter['end']);
			}
		}
		if ($filter['fb_feedback'] != '') {
			$where .= $this->db()->quoteInto(' and fb_feedback = ?', $filter['fb_feedback'], 0);
		}
		if ($filter['is_extended'] != '') {
			$where .= $this->db()->quoteInto(' and is_extended = ?', $filter['is_extended'], 0);
		}
		if ($filter['lose_stock_min'] || $filter['lose_stock_max']) {
			if ($filter['lose_stock_max'] == '') {
				$where .= $this->db()->quoteInto(" and lose_stock > ?", $filter['lose_stock_min'], 0);
			} elseif ($filter['lose_stock_min'] == '') {
				$where .= $this->db()->quoteInto(" and lose_stock < ?", $filter['lose_stock_max'], 0);
			} else {
				$where .= $this->db()->quoteInto(" and lose_stock > ?", $filter['lose_stock_min'], 0) . $this->db()->quoteInto(" and lose_stock < ?", $filter['lose_stock_max'], 0);
			}
		}
		if ($filter['seven_sale_min'] || $filter['seven_sale_max']) {
			if ($filter['seven_sale_max'] == '') {
				$where .= $this->db()->quoteInto(" and seven_sale > ?", $filter['seven_sale_min'], 0);
			} elseif ($filter['seven_sale_min'] == '') {
				$where .= $this->db()->quoteInto(" and seven_sale < ?", $filter['seven_sale_max'], 0);
			} else {
				$where .= $this->db()->quoteInto(" and seven_sale > ?", $filter['seven_sale_min'], 0) . $this->db()->quoteInto(" and seven_sale < ?", $filter['seven_sale_max'], 0);
			}	
		}
		if ($filter['rise_rate_min'] || $filter['rise_rate_max']) {
			if ($filter['rise_rate_max'] == '') {
				$where .= $this->db()->quoteInto(" and rise_rate > ?", $filter['rise_rate_min'], 2);
			} elseif ($filter['rise_rate_min'] == '') {
				$where .= $this->db()->quoteInto(" and rise_rate < ?", $filter['rise_rate_max'], 2);
			} else {
				$where .= $this->db()->quoteInto(" and rise_rate > ?", $filter['rise_rate_min'], 2) . $this->db()->quoteInto(" and rise_rate < ?", $filter['rise_rate_max'], 2);
			}	
		}
		$sql = "select * from sample_cloth_fb where " . $where;
		$sql = $sql . ' limit '.($filter['page'] - 1) * $filter['perPage'].','.$filter['perPage'];
		$countsql = "select count(1) from sample_cloth_fb where ".$where;
		$list = $this->db()->fetchAll($sql);
		foreach ($list as &$val) {
			$val['real_pro'] = strstr($val['real_pro'], '0000') ?? '';
			$val['real_return_sample'] = strstr($val['real_return_sample'], '0000') ?? '';
			$val['log'] = $this->db()->fetchAll("select * from sample_cloth_fb_log where fid=:fid order by handle_time desc", array('fid'=>$val['id']));
			$val['img'] = $this->db()->fetchOne("select thumb_url from p_product where goods_sn like :sku", array('sku'=>$val['sku']."%"));
			$val['days'] = !empty($val['expect_pro']) ? (strtotime($val['expect_pro'])-time()-10*24*3600) <= 0 ? 0 : ((strtotime($val['expect_pro'])-strtotime(date('Y-m-d'))-10*24*3600)/(24*3600)):'';
		}
		
		$res = array();
		$res['list'] = $list;
		$res['count'] = $this->db()->fetchOne($countsql);
		
		return $res;
	}
	/**
	 * 推广
	 * @param int $id
	 * @param string $user
	 * @return number[]|string[]|NULL[]
	 */
	public function extendFb(int $id, string $user) {
		$wdb = $this->db('write_db');
		$wdb->beginTransaction();
		try {
			$param = array(
				'is_extended' => 1,
				'operate_user' => $user
			);
			$wdb->update('sample_cloth_fb', $param, 'id='.$id);
			
			$log = array(
				'type' => 1,
				'operater' => $user,
				'handle_time' => date("Y-m-d H:i:s"),
				'fid' => $id
			);
			$wdb->insert('sample_cloth_fb_log', $log);
			
			$wdb->commit();
			$res = array("opr"=>1,'content'=>"推广成功");
		} catch (Exception $e) {
			$wdb->rollBack();
			$res = array("opr"=>0,'content'=>$e->getMessage());
		}
		return $res;
	}
	/**
	 * 更改FB反馈
	 * @param array $data
	 * @param string $user
	 * @return number[]|string[]|NULL[]
	 */
	public function updateFeedBackById(array $data,string $user) {
		$wdb = $this->db('write_db');
		$wdb->beginTransaction();
		try {
			$wdb->update('sample_cloth_fb', array('fb_feedback'=>$data['feedback'], 'operate_user'=>$user),'id='.$data['id']);
			$log = array(
				'type' => 2,
				'operater' => $user,
				'handle_time' => date("Y-m-d H:i:s"),
				'fid' => $data['id']
			);
			$wdb->insert('sample_cloth_fb_log', $log);
			$wdb->commit();
			$res = array("opr"=>1,'content'=>"FB反馈成功");
		} catch (Exception $e) {
			$wdb->rollBack();
			$res = array("opr"=>0,'content'=>$e->getMessage());
		}
		return $res;
	}
	/**
	 * 预计回样时间
	 * @param array $data
	 * @param string $user
	 * @return number[]|string[]|NULL[]
	 */
	public function updateReturnSampleById(array $data, string $user) {
		$wdb = $this->db('write_db');
		$wdb->beginTransaction();
		try {
			$param = array(
				'return_sample' => $data['return_sample'],
				'operate_user' => $user
			);
			$wdb->update('sample_cloth_fb', $param, 'id='.$data['id']);
			
			$log = array(
				'type' => 4,
				'operater' => $user,
				'handle_time' => date("Y-m-d H:i:s"),
				'fid' => $data['id']
			);
			$wdb->insert('sample_cloth_fb_log', $log);
			$wdb->commit();
			
			$res = array("opr"=>1,'content'=>"预计回样时间更新成功");
		} catch (Exception $e) {
			$wdb->rollBack();
			$res = array("opr"=>0,'content'=>$e->getMessage());
		}
		return $res;
	}
	/**
	 * 预计回大货时间
	 * @param array $data
	 * @param string $user
	 * @return number[]|string[]|NULL[]
	 */
	public function updateExpectProById(array $data, string $user) {
		$wdb = $this->db('write_db');
		$wdb->beginTransaction();
		try {
			$param = array(
				'expect_pro' => $data['expect_pro'],
				'operate_user' => $user
			);
			$wdb->update('sample_cloth_fb', $param, 'id='.$data['id']);
			
			$log = array(
				'type' => 3,
				'operater' => $user,
				'handle_time' => date("Y-m-d H:i:s"),
				'fid' => $data['id']
			);
			$wdb->insert('sample_cloth_fb_log', $log);
			$wdb->commit();
			
			$res = array("opr"=>1,'content'=>"FB反馈成功");
		} catch (Exception $e) {
			$wdb->rollBack();
			$res = array("opr"=>0,'content'=>$e->getMessage());
		}
		return $res;
	}
	public function deleteFb(int $id, string $user) {
		$wdb = $this->db('write_db');
		try {
			$wdb->delete('sample_cloth_fb', 'id='.$id);
			$res = array("opr"=>1,'content'=>"删除成功");
		} catch (Exception $e) {
			$res = array("opr"=>0,'content'=>$e->getMessage());
		}
		return $res;
	}
	/**
	 * 根据批量sku批量获取产品名称
	 * @param array $skus
	 * @return number
	 */
	public function getProductNames(array $skus) {
		$where = $this->db()->quoteInto('goods_sn in (?)', $skus);
		$sql = "select goods_sn,product_name from p_product where {$where}";
		$res=$this->db()->fetchAssoc($sql);
		return  $res + array_flip($skus);
	}
	/**
	 * 获取产品的审核状态和上架状态
	 * @param unknown $sku
	 * @return mixed
	 */
	public function getProductBySku($sku) {
		$sql = "select id,online_status,edit_status from p_product where goods_sn=:goods_sn";
		return $this->db()->fetchRow($sql, array('goods_sn'=>$sku));
	}
	/**
	 * 查看是否存在曝光款
	 * @param unknown $sku
	 */
	public function existFb($sku) {
		return $this->db()->fetchOne("select count(1) from sample_cloth_fb where sku like :sku", array('sku'=>$sku."%"));
	}
	/**
	 * 获取产品分类ID
	 * @param unknown $sku
	 */
	public function getProductCate($sku) {
		$cate_id = $this->db()->fetchOne("select catalog_id from p_product where goods_sn=:sku", array('sku'=>$sku));
		$path = $this->db()->fetchOne("select path from p_product_catalog where id=:id", array('id' => $cate_id));
		return $path;
	}
	/**
	 * 查看是否存在样衣记录
	 * @param unknown $sku
	 * @param string $like
	 */
	public function existSample($sku, $like = false) {
		if ($like) {
			$where = $this->db()->quoteInto('sku like ?', $sku."%");
		} else {
			$where = $this->db()->quoteInto('sku = ?', $sku);
		}
		$sql = "select id from sample_cloth where ".$where;
		return $this->db()->fetchOne($sql);
	}
	/**
	 * 获取同类产品sku列表
	 * @param unknown $sub_sn
	 */
	public function getAllSame($sub_sn) {
		$sql = "select goods_sn from p_product where goods_sn like :sub_sn";
		return $this->db()->fetchAssoc($sql, array('sub_sn'=>$sub_sn."%"));
	}
	/**
	 * 获取产品信息
	 * @param unknown $sku
	 */
	public function getProductInfo($sku) {
		$sql = "select product_name,thumb_url,p2.purchase_price_base,goods_resource_status,purchaser,online_status,edit_status,supplier_sn,sp_name as supplier_name from p_product as p1,p_product_purchase as p2,p_product_supplier p3 where p2.supplier_sn=p3.sp_code and p1.goods_sn=:sku and p2.goods_sn=:sku";
		return $this->db()->fetchRow($sql, array('sku'=>$sku));
	}
	/**
	 * 添加曝光款
	 * @param array $fb
	 */
	public function addFb(array $fb) {
		$this->db('write_db')->insert('sample_cloth_fb', $fb);
	}
	/**
	 * 添加样衣需求
	 * @param array $sample
	 */
	public function addSample(array $sample) {
		$this->db('write_db')->insert('sample_cloth', $sample);
	}
	/**
	 * 获取导出到Excel的列表
	 * @param string $ids
	 */
	public function getExportSamples(string $ids) {
		$sql = $this->db()->quoteInto("select sku from sample_cloth_fb where id in (?)", explode(',', $ids), '0');
		$list = $this->db()->fetchAll($sql);
		foreach ($list as &$val) {
			$val['img'] = $this->db()->fetchOne("select thumb_url from p_product where goods_sn like :sku", array('sku'=>$val['sku']."%"));
		}
		return $list;
	}
}